package com.ruoyi.project.config.qiniu.controller;

import com.qiniu.common.QiniuException;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.config.qiniu.service.IQiniuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/qiniu")
public class QiniuController {
    @Autowired
    private IQiniuService qiniuService;

    /**
     * 七牛云上传
     * @param file 文件
     * @return url
     */
    @PostMapping("/upload")
    public AjaxResult testUpload(@RequestParam("file") MultipartFile file) throws IOException {
        String fileName = generateUniqueFileName(file); // 生成唯一文件名的方法
        File tempFile = null;
        String result = "";
        try {
            // 将 MultipartFile 转换为 File
            tempFile = convertMultipartFileToFile(file);
            // 上传文件
            result = qiniuService.uploadFile(tempFile, fileName);
            System.out.println("访问地址： " + result);
            // 返回成功响应
            return AjaxResult.success(result);
        } finally {
            // 确保删除临时文件
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }

    // 生成唯一文件名的方法，可以根据需要调整生成规则
    private String generateUniqueFileName(MultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        return System.currentTimeMillis() + fileExtension;
    }

    // 辅助方法：将 MultipartFile 转换为 File
    private File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File tempFile = File.createTempFile("temp", null);
        file.transferTo(tempFile);
        return tempFile;
    }
}
